﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace com.sharepointutils.application.Forms
{
    public partial class HttpRequestBuilderForm : Form
    {
        public HttpRequestBuilderForm()
        {
            InitializeComponent();
        }

        private void btn_post_Click(object sender, EventArgs e)
        {
            try
            {

                SaveDefaults();
                //{ "method": "PricingModel.create", "args": [{"Description": "Test Web Service"}] }
                //{ "method": "PricingModel.getList", "args": [] }                
                Uri requestURI = new Uri(comboBox_URL.Text);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURI);

                if (!String.IsNullOrWhiteSpace(comboBox_accept.Text))
                {
                    request.Accept = comboBox_accept.Text;// "application/json; charset=utf-8";
                }

                if (!String.IsNullOrWhiteSpace(comboBox_ContentType.Text))
                {
                    request.ContentType = comboBox_ContentType.Text;// "application/json; charset=utf-8";
                }
               
                //request.Headers.Add("Content-Encoding", "utf-8");

                if (!String.IsNullOrWhiteSpace(comboBox_soapAction.Text))
                {
                    request.Headers.Add("SOAPAction", "\"" + comboBox_soapAction.Text + "\"");
                }

                if (comboBox_authorization.Text == "Basic")
                {
                    byte[] cred = Encoding.ASCII.GetBytes(textBox_username.Text + ":" + textBox_password.Text);
                    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(cred));
                }
                else
                {
                    request.Credentials = new NetworkCredential(textBox_username.Text, textBox_password.Text, textBox_domain.Text);
                }


                request.Method = comboBox_method.Text;// "POST";                

                if (comboBox_method.Text != "GET")
                {
                    request.ContentLength = Encoding.UTF8.GetByteCount(txt_data.Text);
                    using (Stream writer = request.GetRequestStream())
                    {
                        writer.Write(Encoding.UTF8.GetBytes(txt_data.Text), 0, Encoding.UTF8.GetByteCount(txt_data.Text));
                    }
                }

                using (WebResponse response = request.GetResponse())
                {
                    StreamReader sr =
                            new StreamReader(
                                response.GetResponseStream());
                    String result = sr.ReadToEnd();
                    txt_response.Text = result;
                    //var data = new JavaScriptSerializer().Deserialize(result, typeof(object));
                    //JSONResponse jr = new JavaScriptSerializer().Deserialize<JSONResponse>(result);
                }
            }
            catch (WebException ex)
            {
                StreamReader sr = new StreamReader(ex.Response.GetResponseStream());
                String response = sr.ReadToEnd();
                txt_response.Text = "Error: " + Environment.NewLine + ex.Message + Environment.NewLine + "Status: " + Environment.NewLine + ex.Status + Environment.NewLine + "Response: " + Environment.NewLine + ex.Response.Headers.ToString() + Environment.NewLine + response;
            }
            catch (Exception ex)
            {
                txt_response.Text = "Error: " + ex.Message;
            }
        }

        private void HttpRequestBuilderForm_Load(object sender, EventArgs e)
        {
            LoadDefaults();
        }

        private void LoadDefaults()
        {
            textBox_domain.Text = Properties.Settings.Default.Domain;
            textBox_username.Text = Properties.Settings.Default.Username;
            textBox_password.Text = Properties.Settings.Default.Password;
            loadComboBoxDefaults(ref comboBox_URL, Properties.Settings.Default.RequestURLS);
            loadComboBoxDefaults(ref comboBox_soapAction, Properties.Settings.Default.SOAPActions);
        }

        private void SaveDefaults()
        {
            Properties.Settings.Default.SOAPActions = getItemsAsString(ref comboBox_soapAction);
            Properties.Settings.Default.RequestURLS = getItemsAsString(ref comboBox_URL);
            Properties.Settings.Default.Save();
        }


        private void loadComboBoxDefaults(ref ComboBox combo, String array)
        {
            String[] values = array.Split(';');
            foreach (String s in values)
            {
                if (!String.IsNullOrWhiteSpace(s))
                {
                    combo.Items.Add(s);
                }
            }
        }

        private String getItemsAsString(ref ComboBox combo)
        {

            if (!combo.Items.Contains(combo.Text))
            {
                combo.Items.Add(combo.Text);
            }

            System.Text.StringBuilder values = new StringBuilder();
            foreach (String i in combo.Items)
            {
                values.Append(i + ";");
            }
            return values.ToString();
        }
    }
}
